package hamster.csustef.acquisition.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * python工具类
 *
 * @author yin hamaster
 * @date 2021/11/2
 * @descripe 通过系统命令调用执行python文件
 */
@Slf4j
public class PythonUtil {

    private static String python = "/root/IdeaProjects/csust_electric_fee_dw/weather_crawler/venv/bin/python";

    public static int executePython(String path) {
        return executePython(path, false);
    }

    public static int executePython(String path, boolean printOut) {
        return executePython(path, new ArrayList<>(), printOut);
    }

    public static int executePython(String path, List<String> args) {
        return executePython(path, args, false);
    }

    public static int executePython(String path, List<String> args, boolean printOut) {
        if (!new File(path).exists()) {
            System.out.println("所需执行的python文件不存在");
            return -1;
        }

        String[] arguments = new String[args.size() + 2];
        arguments[0] = python;
        arguments[1] = path;
        for (int i = 0; i < args.size(); i++) {
            arguments[i + 2] = args.get(i);
        }
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            if (printOut) {
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                in.close();
            }
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            //返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            return process.waitFor();
        } catch (Exception e) {
            return 1;
        }
    }


}
